<script setup lang="tsx">
import { AddIcon, Delete1Icon } from 'tdesign-icons-vue-next';
import { Link, MessagePlugin, Space } from 'tdesign-vue-next';
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';

import { getLangList } from '@/api/system/basicSetting/7';
import { add, Delete, edit, getList } from '@/api/system/slide';
import IageViewer from '@/components/imageViewer/index.vue';
import MyTable from '@/components/myTable/index.vue';
import OperatingBox from '@/components/operatingBox/index.vue';
import UpLoads from '@/components/upLoads/index.vue';
import { getName } from '@/utils/tool';

const { t } = useI18n();
interface FormDataType {
  id: string | number | null;
  lang: string | number | null;
  pushUrl: string | null;
  imageList: any[];
}
const INITIAL_DATA: FormDataType = {
  id: null,
  lang: null,
  pushUrl: null,
  imageList: [],
};
const form = ref({ ...INITIAL_DATA });
const data = ref([]);
const columns = [
  {
    colKey: 'row-select',
    type: 'multiple' as const,
    width: 50,
  },
  {
    title: 'ID',
    colKey: 'slideId',
    width: 120,
  },
  {
    title: '图片路径',
    colKey: 'imgPath',
    cell: (h: any, { row }: { row: any }) => {
      return <div>{import.meta.env.VITE_PROXY_API_URL + row.imgPath}</div>;
    },
  },
  {
    title: '预览',
    colKey: 'imgPathLook',
  },
  {
    title: '语言',
    colKey: 'lang',
  },
  {
    title: '跳转地址',
    colKey: 'pushUrl',
  },
  {
    title: '状态',
    colKey: 'status',
  },
  {
    title: '操作',
    colKey: 'op',
  },
];

const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 0,
});

const langList = ref<any[]>([]);
// 获取语言
const unGetLangList = async () => {
  try {
    const res = await getLangList({
      pageNum: 1,
      pageSize: 999,
      status: '1',
    });
    langList.value = res.rows;
    unGetList();
  } catch (e) {
    console.log(e);
  }
};
unGetLangList();

const render = () => (
  <>
    <OperatingBox>
      <t-button icon={() => <AddIcon />} onClick={() => unAdd()}>
        新增
      </t-button>
      <t-button theme="danger" icon={() => <Delete1Icon />} onClick={() => deleteClickOp(deleteId.value, true)}>
        批量删除
      </t-button>
    </OperatingBox>
    <MyTable
      columns={columns}
      data={data.value}
      v-model:pagination={pagination.value}
      v-model:selectedRowKeys={deleteId.value}
      rowKey="slideId"
      onUnGetList={unGetList}
    >
      {{
        imgPathLook: (slotProps: any) => (
          <div>
            {slotProps.row.imgPath && <IageViewer img={import.meta.env.VITE_PROXY_API_URL + slotProps.row.imgPath} />}
          </div>
        ),
        lang: (slotProps: any) => <div>{getName('code', slotProps.row.lang, langList.value, 'name')}</div>,
        status: (slotProps: any) => (
          <t-switch
            key={slotProps.row.slideId}
            value={slotProps.row.status}
            onChange={() => unEdit(slotProps.row)}
            size="large"
            custom-value={['1', '0']}
            label={['开', '关']}
          ></t-switch>
        ),
        op: (slotProps: any) => (
          <Space>
            <Link theme="danger" onClick={() => deleteClickOp(slotProps, false)}>
              {t('pages.detailCard.detail.form.delete')}
            </Link>
          </Space>
        ),
      }}
    </MyTable>
  </>
);

const unGetList = async () => {
  try {
    const res = await getList({
      pageNum: pagination.value.defaultCurrent,
      pageSize: pagination.value.defaultPageSize,
    });
    data.value = res.rows;
    pagination.value = {
      ...pagination.value,
      total: res.total,
    };
  } catch (e) {
    console.log(e);
  }
};

/** 添加对话框 */
const open = ref(false);
const uploads = ref();
const unAdd = async () => {
  open.value = true;
  form.value = { ...INITIAL_DATA };
};
const onConfirmAdd = async () => {
  if (form.value.lang == null) {
    return MessagePlugin.warning('请选择语言');
  }
  uploads.value.uploadFiles();
};

const success = () => {
  add(form.value).then(() => {
    open.value = false;
    MessagePlugin.success('提交成功');
    unGetList();
  });
};

// 切换状态
const unEdit = (row: any) => {
  row.status = row.status == '1' ? '0' : '1';
  edit(row).then(() => {
    MessagePlugin.success('操作成功');
    unGetList();
  });
};

// 删除
const confirmVisible = ref(false);
const deleteId = ref([]);
const onConfirmDelete = () => {
  const ids = deleteId.value.join(',');
  Delete(ids).then(() => {
    confirmVisible.value = false;
    MessagePlugin.success('删除成功');
    unGetList();
  });
};

const deleteClickOp = (value: any, isSingle: boolean) => {
  if (isSingle && !value.length) {
    MessagePlugin.warning('请先勾选数据');
    return;
  }
  confirmVisible.value = true;
  deleteId.value = isSingle ? value : [value.row.slideId];
};

const onCancel = () => {
  if (deleteId.value.length < 2) {
    deleteId.value = [];
  }
};
</script>

<template>
  <div>
    <render />
    <!-- 对话框 -->
    <t-dialog v-model:visible="open" header="添加幻灯片" width="50%" @confirm="onConfirmAdd">
      <t-select v-model="form.lang" placeholder="请选择语言" style="width: 240px; margin-bottom: 10px">
        <t-option v-for="item in langList" :key="item.code" :label="item.name" :value="item.code" />
      </t-select>
      <t-input
        v-model="form.pushUrl"
        :style="{ width: '240px', 'margin-bottom': '10px' }"
        placeholder="请输入跳转地址"
      />
      <up-loads
        v-if="open"
        ref="uploads"
        :key="form.imageList[form.imageList.length - 1]"
        v-model:image="form.imageList"
        @success="success"
      ></up-loads>
    </t-dialog>
    <t-dialog
      v-model:visible="confirmVisible"
      header="确认删除当前所选项目？"
      body="删除后，数据将被清空，且无法恢复"
      :on-cancel="onCancel"
      @confirm="onConfirmDelete"
    />
  </div>
</template>
